<template>
  <a-form id="formForgotPassword" ref="formForgotPassword" :form="form">
    <!-- <a-form-item label="登录账号">
      <a-input
        v-decorator="['username', {rules: [{ required: true, message: '请输入用户名称' }], validateTrigger: ['change', 'blur']}]"
        type="text"
        placeholder="登录账号"
      />
    </a-form-item> -->

    <a-form-item label="账号手机" class="reset-form-item">
      <a-input
        v-decorator="['mobile', {
          rules: [{ required: true, message: '请输入正确的手机号', pattern: /^1[3456789]\d{9}$/ }, { validator: this.handlePhoneCheck } ],
          validateTrigger: ['change', 'blur'],
          initialValue: isSet && user && user.teacher && user.teacher.phone || ''
        }]"
        :disabled="isSet"
        placeholder="11 位手机号"
      >
        <!-- <a-select slot="addonBefore" default-value="+86">
                  <a-select-option value="+86">+86</a-select-option>
                </a-select> -->
      </a-input>
    </a-form-item>
    <a-row>
      <a-col class="gutter-row" :span="14">
        <a-form-item label="验证码" class="reset-form-item">
          <a-input v-decorator="['captcha', {rules: [{ required: true, message: '请输入验证码' }], validateTrigger: 'blur'}]" type="text" placeholder="验证码">
            <a-icon slot="prefix" type="mail" :style="{ color: 'rgba(0,0,0,.25)' }" />
          </a-input>
        </a-form-item>
      </a-col>
      <a-col class="gutter-row" :span="10">
        <a-button
          style="font-size:12px"
          class="getCaptcha primary-btn"
          :disabled="state.smsSendBtn"
          @click.stop.prevent="getCaptcha"
          v-text="!state.smsSendBtn && '获取验证码'||(state.time+' s')"
        />
      </a-col>
    </a-row>
    <a-form-item style="margin-top: 20px">
      <nuxt-link v-if="isSet" class="login" to="/system/Account" style="float:right">返回</nuxt-link>
      <nuxt-link v-else class="login" to="/users/login/" style="float:right">返回登录页面</nuxt-link>
      <a-button
        class="primary-btn forgetPassword-button"
        html-type="submit"
        :loading="registerBtn"
        :disabled="registerBtn"
        @click.stop.prevent="handleSubmit"
      >重置密码
      </a-button>

    </a-form-item>

  </a-form>

</template>

<script>
import { mixinDevice } from '@/utils/mixin.js'
import { mapState } from 'vuex'
// import md5 from 'md5'

export default {
  name: 'ForgotPassword',
  layout: 'login-layout',
  auth: false,
  mixins: [mixinDevice],
  data () {
    return {
      form: process.client ? this.$form.createForm(this) : null,
      interval: null,
      state: {
        time: 60,
        smsSendBtn: false,
        progressColor: '#FF0000'
      },
      registerBtn: false,

      isSet: false
    }
  },

  computed: {
    ...mapState({
      user: state => state.auth && state.auth.user || {}
    })
  },

  watch: {
    $route: {
      handler (t, f) {
        this.isSet = false
        if (t.name === 'System-Verification') {
          this.isSet = true
          this.$parent && this.$parent.$parent && this.$parent.$parent.$parent && this.$parent.$parent.$parent.$parent && (this.$parent.$parent.$parent.$parent.isSet = true)
        }
      },
      immediate: true
    }
  },

  methods: {
    handlePhoneCheck (rule, value, callback) {
      callback()
    },
    async handleSubmit () {
      const { form: { validateFieldsAndScroll }} = this
      const that = this
      validateFieldsAndScroll({ force: true }, (err, values) => {
        if (!err) {
          this.forgotPassword({ ...values })
            .then((res) => {
              if (res.code !== '000000' || res.code === '020000' || res.code === '040001') {
                this.$notification.error({
                  message: res.mesg || res.data,
                  description: `请确认后重新输入`
                })
                this.state.time = 60
                this.state.smsSendBtn = false
                window.clearInterval(this.interval)
              } else {
                if (values.captcha !== undefined) {
                  if (that.isSet) {
                    this.$router.push({ name: 'System-SetPassword', params: { ...values }})
                  } else {
                    this.$router.push({ name: 'users-ResetPassword', params: { ...values }})
                  }
                } else {
                  this.$router.push({ name: 'users-ForgotPasswordResult', params: { ...values }})
                }
              }
            }
            )
        }
      })
    },
    async forgotPassword (params) {
      const res = await this.$authlessApi.forgotPassword(params)
      return res
    },
    async getCaptcha (e) {
      e.preventDefault()
      const { form: { validateFields }, state, $message } = this

      validateFields(['mobile'], { force: true },
        (err, values) => {
          if (!err) {
            state.smsSendBtn = true

            const interval = window.setInterval(() => {
              if (state.time-- <= 0) {
                state.time = 60
                state.smsSendBtn = false
                window.clearInterval(interval)
              }
            }, 1000)
            this.interval = interval
            const hide = $message.loading('验证码发送中..', 0)

            this.getSmsCaptcha({ username: values.username, mobile: values.mobile, type: 3 }, hide)
          }
        }
      )
    },
    async getSmsCaptcha (params, hide) {
      const { state } = this
      try {
        const res = await this.$authlessApi.getCaptcha(params)
        console.log(res)
        if (res) {
          if (res.code !== '000000') {
            this.$notification.error({
              message: res.mesg || res.data,
              description: `请确认后重新输入`
            })
            setTimeout(hide, 1)
            window.clearInterval(this.interval)
            state.time = 60
            state.smsSendBtn = false
          } else {
            setTimeout(hide, 2500)
            // window.clearInterval(this.interval)
            // state.time = 60
            // state.smsSendBtn = false
            this.$notification.success({
              message: '提示',
              description: '验证码获取成功,请注意查看',
              duration: 8
            })
          }
        }
      } catch (err) {
        setTimeout(hide, 1)
        window.clearInterval(this.interval)
        state.time = 60
        state.smsSendBtn = false
      }
    }

  }
}
</script>
<style lang="less" scoped>
.main{
    background-position: center;
    background-size: cover;
    position: absolute;
    top:0;
    left: 0;
    right: 0;
    bottom: 0;
    .form{
        padding:50px;
        position: absolute;
        top:50%;
        left:50%;
        transform: translate(-50%,-50%);
        background: #fff;
        width: 70%;
        border-radius: 10px;
        .logo{
          img{
            width: 40%;
            height: auto;
            margin-bottom: 30px;
          }
        }
        .lost-pwd{
          display: inline-block;
          color:#1890ff;
          cursor: pointer;
        }
        /deep/ .ant-btn{
          width: 40%;
          border-radius: 20px;
          padding:20px;
          line-height: 0;
          margin-top:30px;
        }
        .form-right{
          .small-bg{
            img{
              width: 80%;
              height: auto;
              margin-left: calc(10% + 10px);
              margin-top: -50px;
            }

          }
        }
        .getCaptcha {
          display: block;
          width: calc(100% - 12px);
          // height: 40px;
          margin-top: 27px;
          padding: 0;
          margin-left: 12px;
        }
    }
}

.reset-form-item {
  height: 83px;

}

/deep/ .ant-form-item-label {
  line-height: unset !important;
}
</style>
